from fastapi import APIRouter, HTTPException, Path, Query
from typing import List, Optional
from ..models import Item, ItemCreate, ItemUpdate, ApiResponse

# 创建路由器
router = APIRouter(
    prefix="/api/items",
    tags=["items"],
    responses={404: {"description": "未找到"}},
)

# 模拟数据库
items_db = [
    Item(id=1, name="笔记本电脑", description="高性能笔记本电脑", price=5999.99, is_available=True),
    Item(id=2, name="智能手机", description="最新款智能手机", price=3999.99, is_available=True),
    Item(id=3, name="耳机", description="无线蓝牙耳机", price=899.99, is_available=False)
]

# 获取所有商品
@router.get("/", response_model=List[Item])
async def get_items(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回的最大记录数"),
    available: Optional[bool] = Query(None, description="按可用性筛选")
):
    filtered_items = items_db
    
    # 按可用性筛选
    if available is not None:
        filtered_items = [item for item in filtered_items if item.is_available == available]
    
    # 分页
    return filtered_items[skip : skip + limit]

# 获取单个商品
@router.get("/{item_id}", response_model=Item)
async def get_item(item_id: int = Path(..., ge=1, description="商品ID")):
    item = next((item for item in items_db if item.id == item_id), None)
    if item is None:
        raise HTTPException(status_code=404, detail="商品未找到")
    return item

# 创建新商品
@router.post("/", response_model=Item, status_code=201)
async def create_item(item_create: ItemCreate):
    # 生成新ID (简单实现，实际应用中可能使用数据库自增ID或UUID)
    new_id = max(item.id for item in items_db) + 1 if items_db else 1
    
    # 创建新商品
    new_item = Item(
        id=new_id,
        name=item_create.name,
        description=item_create.description,
        price=item_create.price,
        is_available=item_create.is_available
    )
    
    items_db.append(new_item)
    return new_item

# 更新商品
@router.put("/{item_id}", response_model=Item)
async def update_item(
    item_id: int = Path(..., ge=1, description="商品ID"),
    item_update: ItemUpdate = ...
):
    for i, item in enumerate(items_db):
        if item.id == item_id:
            # 更新非空字段
            update_data = item_update.dict(exclude_unset=True)
            updated_item = item.copy(update=update_data)
            items_db[i] = updated_item
            return updated_item
    
    raise HTTPException(status_code=404, detail="商品未找到")

# 删除商品
@router.delete("/{item_id}", response_model=ApiResponse)
async def delete_item(item_id: int = Path(..., ge=1, description="商品ID")):
    for i, item in enumerate(items_db):
        if item.id == item_id:
            del items_db[i]
            return ApiResponse(
                success=True,
                message=f"ID为{item_id}的商品已删除"
            )
    
    raise HTTPException(status_code=404, detail="商品未找到")